//
//  SimpleDB.m
//  uteped_sdk
//
//  Created by mateng on 2024/2/27.
//

#import "SimpleDB.h"

@interface SimpleDB ()

@property(nonatomic, strong) NSMutableDictionary *tables;

@end

@implementation SimpleDB

- (id)initWithName:(NSString*)dbName {
    if (self = [super init]) {
        self.tables = [[NSMutableDictionary alloc] init];
        NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)  lastObject];
        NSString *fileName = [doc stringByAppendingPathComponent:dbName];
        self.db = [FMDatabase databaseWithPath:fileName];
    }
    
    return self;
}

- (nonnull NSString *)getTable:(nonnull NSString *)name {
    return [self.tables objectForKey:name];
}

- (void)putTable:(nonnull NSString *)name table:(nonnull NSString *)table {
    if ([self.tables.allKeys containsObject:name]) {
        return;
    }
    
    [self.tables setObject:table forKey:name];
}

- (BOOL)isTableOK:(NSString *)name{
    FMResultSet *rs = [self.db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", name];
    while ([rs next]){
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %ld", count);
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)open {
    BOOL success = [self.db isOpen];
    if (!success) {
        success = [self.db open];
    }
    return success;
}

- (void)close {
    if ([self.db isOpen]) {
        [self.db close];
    }
}

@end
